package com.sna.snaapplication.service.core;

import com.sna.snaapplication.entity.usercore.Role;
import com.sna.snaapplication.entity.usercore.User;
import com.sna.snaapplication.entity.usercore.login.MyUserDetails;
import com.sna.snaapplication.mapper.UserMapper;
import com.sna.snaapplication.service.UserSys.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleService roleService;


    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        MyUserDetails myUserDetails = new MyUserDetails();

        User user = userMapper.findByUserName(username);

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        //从表role查询当前要登录用户的 角色ID
        Role role = roleService.FindByUserId(user.getUserId());

        List<Role> roles = new ArrayList<>();
        roles.add(role);
        user.setRoles(roles);

        if(roles==null){
            System.out.println("在 MyUserDetailsService+user"+user);
            throw new RuntimeException("角色查询不到");
        }


        System.out.println("role"+user.getRoles());
        myUserDetails.setUserName(user.getUserName());
        myUserDetails.setPassword(user.getPassword());
        myUserDetails.setRoles(user.getRoles());

        //加入目的：需要在插入、修改数据时，自动插入用户的ID
        myUserDetails.setUserId(user.getUserId());

        System.out.println("在MyUserDetailsService"+"myUserDetails"+myUserDetails);

        return myUserDetails;
    }

}
